<?php

namespace app\common\model;

use app\common\library\MemberVo;
use app\common\library\TencentMap;
use think\Env;
use think\Exception;
use think\Model;

/**
 * 模型
 */
class ServiceShop extends Model
{

    // 表名
    protected $name = 'service_shop';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    protected $deleteTime = false;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';


    // 追加属性
    protected $append = [

    ];

    public function member()
    {
        return $this->belongsTo('Member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function type()
    {
        return $this->belongsTo('Member', 'member_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function service()
    {
        return $this->belongsTo('Service', 'service_type', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function province()
    {
        return $this->belongsTo('Amap', 'province', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function city()
    {
        return $this->belongsTo('Amap', 'city', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function shop()
    {
        return $this->belongsTo('Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function districts()
    {
        return $this->belongsTo('Amap', 'districts', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function setCoverImgAttr($value)
    {
        if (!empty($value)){
            $arr = parse_url($value);
            return $arr['path'];
        }
        return '';
    }

    public function getCoverImgAttr($value) {
        return $value ? Env::get('app.app_host').$value : '';
    }

    /**
     * 获取商机列表
     * @param $params
     * @return array
     * @throws \think\exception\DbException
     */
    public static function getList($params)
    {
        $where['type'] = $params['type'];
        if ($params['self'] == 1)
            $where['member_id'] = MemberVo::instance()->getMemberId();
        $to = '';
        $list = self::field('cover_img,id,type,name,phone,main_business,province,city,districts,address,latitude,longitude')->where($where)->order('id desc')->paginate(10)->each(function ($item) use (&$to) {
            $to = $to.$item['latitude'].','.$item['longitude'].';';
            return $item;
        });
        $list_arr = $list->toArray();
        if (!empty($list_arr['data'])){
            $to = rtrim($to,';');
            $params_new = ['from' => $params['lat'] . ',' . $params['lng'], 'to' => $to,];
            $distance = TencentMap::instance()->matrix($params_new);
            foreach ($list_arr['data'] as $key=>&$v){
                $v['distance'] = round($distance['rows'][0]['elements'][$key]['distance'] / 1000,2).'公里';
            }
        }
        return $list_arr;
    }







}
